
<!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>管理员后台 - 选择题练习平台</title>
        <style>
            body {
                font-family: 'Microsoft YaHei', Arial, sans-serif;
                margin: 0;
                padding: 20px;
                background-color: #f5f5f5;
            }
            .container {
                max-width: 1200px;
                margin: 0 auto;
                background: white;
                padding: 30px;
                border-radius: 10px;
                box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            }
            h1 {
                color: #333;
                text-align: center;
                margin-bottom: 30px;
            }
            .section {
                margin-bottom: 30px;
                padding: 20px;
                border: 1px solid #ddd;
                border-radius: 5px;
            }
            .section h2 {
                color: #555;
                margin-top: 0;
            }
            label {
                display: block;
                margin-bottom: 5px;
                font-weight: bold;
            }
            select, textarea, button {
                width: 100%;
                padding: 10px;
                margin-bottom: 15px;
                border: 1px solid #ddd;
                border-radius: 4px;
                font-size: 14px;
            }
            textarea {
                height: 200px;
                resize: vertical;
                font-family: monospace;
            }
            button {
                background-color: #007bff;
                color: white;
                border: none;
                cursor: pointer;
                font-weight: bold;
            }
            button:hover {
                background-color: #0056b3;
            }
            .scores-table {
                width: 100%;
                border-collapse: collapse;
                margin-top: 15px;
            }
            .scores-table th, .scores-table td {
                border: 1px solid #ddd;
                padding: 12px;
                text-align: left;
            }
            .scores-table th {
                background-color: #f8f9fa;
                font-weight: bold;
            }
            .scores-table tr:nth-child(even) {
                background-color: #f9f9f9;
            }
            .message {
                padding: 12px 16px;
                margin: 10px 0;
                border-radius: 6px;
                font-weight: 500;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                position: relative;
                overflow: hidden;
            }
            .success {
                background-color: #d4edda;
                color: #155724;
                border: 1px solid #c3e6cb;
                border-left: 4px solid #28a745;
            }
            .error {
                background-color: #f8d7da;
                color: #721c24;
                border: 1px solid #f5c6cb;
                border-left: 4px solid #dc3545;
            }
            .warning {
                background-color: #fff3cd;
                color: #856404;
                border: 1px solid #ffeaa7;
                border-left: 4px solid #ffc107;
            }
            .info {
                background-color: #d1ecf1;
                color: #0c5460;
                border: 1px solid #bee5eb;
                border-left: 4px solid #17a2b8;
            }

            /* 动画效果 */
            @keyframes slideIn {
                from {
                    opacity: 0;
                    transform: translateY(-10px);
                }
                to {
                    opacity: 1;
                    transform: translateY(0);
                }
            }

            @keyframes fadeOut {
                from {
                    opacity: 1;
                    transform: translateY(0);
                }
                to {
                    opacity: 0;
                    transform: translateY(-10px);
                }
            }

            .message.fade-out {
                animation: fadeOut 0.3s ease-in forwards;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <h1>管理员后台</h1>
            
            <div class="section">
                <h2>⚙️ 大语言模型配置</h2>
                <div style="margin-bottom: 20px;">
                    <button onclick="loadLLMConfigs()" style="width: auto; margin-right: 10px;">刷新配置列表</button>
                    <button onclick="showLLMConfigForm()" style="width: auto; background-color: #28a745;">添加新配置</button>
                </div>
                
                <!-- 配置表单 -->
                <div id="llmConfigForm" style="display: none; background-color: #f8f9fa; padding: 20px; border-radius: 5px; margin-bottom: 20px;">
                    <h3 id="llmFormTitle">添加新配置</h3>
                    
                    <!-- 快速选择模板 -->
                    <div style="margin-bottom: 15px; padding: 10px; background-color: #e9ecef; border-radius: 5px;">
                        <label style="font-weight: bold; margin-bottom: 5px; display: block;">快速选择模型模板:</label>
                        <button type="button" onclick="fillDeepSeekTemplate()" style="width: auto; margin-right: 10px; padding: 5px 10px; font-size: 12px; background-color: #007bff;">DeepSeek</button>
                        <button type="button" onclick="fillGeminiTemplate()" style="width: auto; margin-right: 10px; padding: 5px 10px; font-size: 12px; background-color: #4285f4;">Gemini</button>
                        <button type="button" onclick="fillOpenAITemplate()" style="width: auto; margin-right: 10px; padding: 5px 10px; font-size: 12px; background-color: #10a37f;">OpenAI</button>
                        <button type="button" onclick="clearTemplate()" style="width: auto; padding: 5px 10px; font-size: 12px; background-color: #6c757d;">清空</button>
                    </div>
                    
                    <form id="editLLMConfigForm">
                        <input type="hidden" id="llmConfigId" value="">
                        
                        <label for="configName">配置名称:</label>
                        <input type="text" id="configName" placeholder="例如：DeepSeek主配置、Gemini配置等" required>
                        
                        <label for="apiKey">API Key:</label>
                        <input type="password" id="apiKey" placeholder="请输入API密钥" required>
                        
                        <label for="baseUrl">Base URL:</label>
                        <input type="text" id="baseUrl" placeholder="例如：https://api.deepseek.com/v1 或 https://generativelanguage.googleapis.com/v1beta/models" required>
                        
                        <label for="modelName">模型名称:</label>
                        <input type="text" id="modelName" placeholder="例如：deepseek-chat 或 gemini-2.0-flash" required>
                        
                        <label>
                            <input type="checkbox" id="isActive"> 设为当前激活配置
                        </label>
                        
                        <div style="margin-top: 15px;">
                            <button type="submit" style="width: auto; margin-right: 10px;">保存配置</button>
                            <button type="button" onclick="hideLLMConfigForm()" style="width: auto; background-color: #6c757d;">取消</button>
                        </div>
                    </form>
                </div>
                
                <!-- 配置列表 -->
                <div id="llmConfigsList"></div>
                <div id="llmConfigMessage"></div>
            </div>
            
            <div class="section">
                <h2>🤖 AI智能命题</h2>
                <form id="aiGenerateForm">
                    <div style="display: flex; gap: 20px; margin-bottom: 15px;">
                        <div style="flex: 1;">
                            <label for="knowledgePointInput">输入知识点:</label>
                            <textarea id="knowledgePointInput" placeholder="请输入要生成题目的知识点，例如：Python基础语法、数据库基本概念、网络协议基础、算法与数据结构、信息安全基础等。AI将根据您输入的知识点自动生成高质量的选择题。" style="height: 100px;"></textarea>
                        </div>
                        <div style="flex: 0 0 200px;">
                            <label for="questionCount">题目数量:</label>
                            <input type="number" id="questionCount" value="5" min="1" max="20" style="width: 100%; margin-bottom: 10px;">
                            
                            <label for="difficultyLevel">难度等级:</label>
                            <select id="difficultyLevel" style="width: 100%; margin-bottom: 10px;">
                                <option value="">自动选择</option>
                                <option value="easy">简单</option>
                                <option value="medium">中等</option>
                                <option value="hard">困难</option>
                            </select>
                            
                            <label for="topicCategory">主题分类:</label>
                            <input type="text" id="topicCategory" placeholder="如：基础概念、实践应用" style="width: 100%; margin-bottom: 10px;">
                        </div>
                    </div>
                    
                    <div style="margin-bottom: 15px;">
                        <label>
                            <input type="checkbox" id="batchMode"> 批量生成模式
                        </label>
                        <div id="batchModeOptions" style="display: none; margin-top: 10px;">
                            <label for="batchPrompts">批量提示词（每行一个）:</label>
                            <textarea id="batchPrompts" placeholder='输入多个知识点，每行一个：
Python变量与数据类型
条件语句与循环结构
函数定义与调用
列表与字典操作' style="height: 80px;"></textarea>
                        </div>
                    </div>
                    
                    <button type="submit" style="background-color: #28a745;">🚀 AI生成题目</button>
                </form>
                <div id="aiGenerateMessage"></div>
            </div>
            
            <div class="section">
                <h2>批量题目设置</h2>
                <form id="questionsForm">
                    <label for="questionsData">题目数据 (JSON格式):</label>
                    <textarea id="questionsData" placeholder='支持两种输入方式：

1. 自然语言描述（推荐）：
例如："生成5道关于Python基础语法的选择题"
或："创建一些关于数据库基本概念的题目"

2. JSON格式的题目数据：
[
  {
    "question_content": "以下哪个是Python的关键字？",
    "option_a": "A. hello",
    "option_b": "B. world",
    "option_c": "C. def",
    "option_d": "D. python",
    "answer": "C",
    "knowledge_point": "Python关键字是语言的保留字，不能用作变量名。"
  }
]'></textarea>
                    <button type="submit">批量更新题目</button>
                </form>
                <div id="questionsMessage"></div>
            </div>
            
            <div class="section">
                <h2>📚 题库管理</h2>
                
                <!-- 当前激活题库显示 -->
                <div style="background-color: #e9ecef; padding: 15px; border-radius: 5px; margin-bottom: 20px;">
                    <h3 style="margin-top: 0; color: #0056b3;">🎯 当前激活题库</h3>
                    <p style="margin-bottom: 10px; color: #666;">激活的题库将用于前台显示题目和智能生成题目的保存。</p>
                    <div id="currentActiveBank" style="font-size: 16px; font-weight: bold; color: #28a745;">
                        正在加载...
                    </div>
                </div>
                
                <div style="margin-bottom: 20px;">
                    <button onclick="loadQuestionBanks()" style="width: auto; margin-right: 10px;">刷新题库列表</button>
                    <button onclick="showQuestionBankForm()" style="width: auto; background-color: #28a745; margin-right: 10px;">创建新题库</button>
                    <button onclick="showBatchMoveForm()" style="width: auto; background-color: #17a2b8; margin-right: 10px;">📦 批量移动题目</button>
                    <button onclick="showBatchCopyForm()" style="width: auto; background-color: #28a745;">📋 批量复制题目</button>
                </div>
                
                <!-- 批量移动题目表单 -->
                <div id="batchMoveForm" style="display: none; background-color: #f8f9fa; padding: 20px; border-radius: 5px; margin-bottom: 20px;">
                    <h3>📦 批量移动题目到题库</h3>

                    <!-- 目标题库选择 -->
                    <div style="margin-bottom: 20px;">
                        <label for="targetQuestionBank" style="font-weight: bold; display: block; margin-bottom: 5px;">🎯 目标题库:</label>
                        <select id="targetQuestionBank" style="width: 100%; padding: 10px; margin-top: 5px; border: 1px solid #ddd; border-radius: 4px;">
                            <option value="">请选择目标题库</option>
                        </select>
                    </div>

                    <!-- 源题库选择 -->
                    <div style="margin-bottom: 20px;">
                        <label for="sourceQuestionBank" style="font-weight: bold; display: block; margin-bottom: 5px;">📚 源题库:</label>
                        <select id="sourceQuestionBank" onchange="loadSourceQuestions()" style="width: 100%; padding: 10px; margin-top: 5px; border: 1px solid #ddd; border-radius: 4px;">
                            <option value="">请选择源题库</option>
                        </select>
                        <small style="color: #666;">选择要移动题目的源题库</small>
                    </div>

                    <!-- 题目选择区域 -->
                    <div id="questionSelectionArea" style="display: none;">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                            <label style="font-weight: bold;">📝 选择要移动的题目:</label>
                            <div>
                                <button type="button" onclick="selectAllQuestions()" style="padding: 5px 10px; margin-right: 5px; background: #28a745; color: white; border: none; border-radius: 3px; font-size: 12px;">全选</button>
                                <button type="button" onclick="unselectAllQuestions()" style="padding: 5px 10px; background: #6c757d; color: white; border: none; border-radius: 3px; font-size: 12px;">取消全选</button>
                            </div>
                        </div>

                        <!-- 题目列表 -->
                        <div id="questionsList" style="max-height: 400px; overflow-y: auto; border: 1px solid #ddd; border-radius: 4px; padding: 10px; background: white;">
                            <div style="text-align: center; color: #666; padding: 20px;">请先选择源题库</div>
                        </div>

                        <!-- 选择统计 -->
                        <div id="selectionStats" style="margin-top: 10px; padding: 10px; background: #e9ecef; border-radius: 4px; font-size: 14px;">
                            <span id="selectedCount">已选择: 0</span> 道题目
                        </div>
                    </div>

                    <!-- 操作按钮 -->
                    <div style="margin-top: 20px; text-align: right;">
                        <button onclick="batchMoveQuestions()" style="padding: 10px 20px; margin-right: 10px; background: #007bff; color: white; border: none; border-radius: 4px;">🚀 开始移动</button>
                        <button onclick="hideBatchMoveForm()" style="padding: 10px 20px; background: #6c757d; color: white; border: none; border-radius: 4px;">❌ 取消</button>
                    </div>
                </div>

                <!-- 批量复制题目表单 -->
                <div id="batchCopyForm" style="display: none; background-color: #e8f5e8; padding: 20px; border-radius: 5px; margin-bottom: 20px; border: 2px solid #28a745;">
                    <h3>📋 批量复制题目到题库</h3>
                    <p style="color: #155724; background: #d4edda; padding: 10px; border-radius: 4px; margin-bottom: 20px;">
                        💡 <strong>复制模式</strong>：题目将被复制到目标题库，原题库中的题目保持不变
                    </p>

                    <!-- 目标题库选择 -->
                    <div style="margin-bottom: 20px;">
                        <label for="copyTargetQuestionBank" style="font-weight: bold; display: block; margin-bottom: 5px;">🎯 目标题库:</label>
                        <select id="copyTargetQuestionBank" style="width: 100%; padding: 10px; margin-top: 5px; border: 1px solid #ddd; border-radius: 4px;">
                            <option value="">请选择目标题库</option>
                        </select>
                    </div>

                    <!-- 源题库选择 -->
                    <div style="margin-bottom: 20px;">
                        <label for="copySourceQuestionBank" style="font-weight: bold; display: block; margin-bottom: 5px;">📚 源题库:</label>
                        <select id="copySourceQuestionBank" onchange="loadCopySourceQuestions()" style="width: 100%; padding: 10px; margin-top: 5px; border: 1px solid #ddd; border-radius: 4px;">
                            <option value="">请选择源题库</option>
                        </select>
                        <small style="color: #666;">选择要复制题目的源题库</small>
                    </div>

                    <!-- 题目选择区域 -->
                    <div id="copyQuestionSelectionArea" style="display: none;">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                            <label style="font-weight: bold;">📝 选择要复制的题目:</label>
                            <div>
                                <button type="button" onclick="selectAllCopyQuestions()" style="padding: 5px 10px; margin-right: 5px; background: #28a745; color: white; border: none; border-radius: 3px; font-size: 12px;">全选</button>
                                <button type="button" onclick="unselectAllCopyQuestions()" style="padding: 5px 10px; background: #6c757d; color: white; border: none; border-radius: 3px; font-size: 12px;">取消全选</button>
                            </div>
                        </div>

                        <!-- 题目列表 -->
                        <div id="copyQuestionsList" style="max-height: 400px; overflow-y: auto; border: 1px solid #ddd; border-radius: 4px; padding: 10px; background: white;">
                            <div style="text-align: center; color: #666; padding: 20px;">请先选择源题库</div>
                        </div>

                        <!-- 选择统计 -->
                        <div id="copySelectionStats" style="margin-top: 10px; padding: 10px; background: #e9ecef; border-radius: 4px; font-size: 14px;">
                            <span id="copySelectedCount">已选择: 0</span> 道题目
                        </div>
                    </div>

                    <!-- 操作按钮 -->
                    <div style="margin-top: 20px; text-align: right;">
                        <button onclick="batchCopyQuestions()" style="padding: 10px 20px; margin-right: 10px; background: #28a745; color: white; border: none; border-radius: 4px;">📋 开始复制</button>
                        <button onclick="hideBatchCopyForm()" style="padding: 10px 20px; background: #6c757d; color: white; border: none; border-radius: 4px;">❌ 取消</button>
                    </div>
                </div>

                <!-- 创建/编辑题库表单 -->
                <div id="questionBankForm" style="display: none; background-color: #f8f9fa; padding: 20px; border-radius: 5px; margin-bottom: 20px;">
                    <h3 id="bankFormTitle">创建新题库</h3>
                    <form id="editQuestionBankForm">
                        <input type="hidden" id="questionBankId" value="">
                        
                        <label for="bankName">题库名称:</label>
                        <input type="text" id="bankName" placeholder="请输入题库名称" required>
                        
                        <label for="bankDescription">题库描述:</label>
                        <textarea id="bankDescription" style="height: 80px;" placeholder="请输入题库描述（可选）"></textarea>
                        
                        <div style="margin-top: 15px;">
                            <button type="submit" style="width: auto; margin-right: 10px;">保存题库</button>
                            <button type="button" onclick="hideQuestionBankForm()" style="width: auto; background-color: #6c757d;">取消</button>
                        </div>
                    </form>
                </div>
                
                <!-- 题库操作消息显示 -->
                <div id="questionBankMessage"></div>

                <!-- 题库列表 -->
                <div id="questionBanksList"></div>
                <div id="questionBanksMessage"></div>
            </div>
            
            <div class="section">
                <h2>📝 题目管理</h2>
                
                <!-- 题目统计信息 -->
                <div id="questionStats" style="background-color: #e9ecef; padding: 15px; border-radius: 5px; margin-bottom: 20px;">
                    <div style="display: flex; gap: 30px; align-items: center; flex-wrap: wrap;">
                        <div>
                            <strong>总题目数：</strong>
                            <span id="totalQuestions" style="color: #007bff; font-size: 18px; font-weight: bold;">0</span>
                        </div>
                        <div>
                            <strong>当前显示：</strong>
                            <span id="filteredQuestions" style="color: #28a745; font-size: 18px; font-weight: bold;">0</span>
                        </div>
                        <div>
                            <strong>已分类题目：</strong>
                            <span id="categorizedQuestions" style="color: #17a2b8; font-size: 18px; font-weight: bold;">0</span>
                        </div>
                        <div>
                            <strong>未分类题目：</strong>
                            <span id="uncategorizedQuestions" style="color: #ffc107; font-size: 18px; font-weight: bold;">0</span>
                        </div>
                    </div>
                </div>
                
                <div style="margin-bottom: 20px;">
                    <button onclick="loadQuestions()" style="width: auto; margin-right: 10px;">刷新题目列表</button>
                    <button onclick="showCreateForm()" style="width: auto; background-color: #28a745;">添加新题目</button>
                </div>
                
                <!-- 题目搜索和筛选 -->
                <div style="background-color: #f8f9fa; padding: 15px; border-radius: 5px; margin-bottom: 20px;">
                    <div style="display: flex; gap: 15px; align-items: center; flex-wrap: wrap;">
                        <div style="flex: 1; min-width: 200px;">
                            <label for="searchQuestion" style="display: block; margin-bottom: 5px; font-weight: bold;">搜索题目:</label>
                            <input type="text" id="searchQuestion" placeholder="输入关键词搜索题目内容..." style="width: 100%;" oninput="filterQuestions()">
                        </div>
                        <div style="min-width: 150px;">
                            <label for="filterQuestionBank" style="display: block; margin-bottom: 5px; font-weight: bold;">筛选题库:</label>
                            <select id="filterQuestionBank" style="width: 100%;" onchange="filterQuestions()">
                                <option value="">全部题库</option>
                            </select>
                        </div>
                        <div style="align-self: flex-end;">
                            <button onclick="showUncategorizedQuestions()" style="width: auto; background-color: #ffc107; color: #000; padding: 8px 15px; margin-right: 10px;">显示未分类</button>
                            <button onclick="clearFilters()" style="width: auto; background-color: #6c757d; padding: 8px 15px;">清除筛选</button>
                        </div>
                    </div>
                </div>
                
                <!-- 创建/编辑题目表单 -->
                <div id="questionForm" style="display: none; background-color: #f8f9fa; padding: 20px; border-radius: 5px; margin-bottom: 20px;">
                    <h3 id="formTitle">添加新题目</h3>
                    <form id="editQuestionForm">
                        <input type="hidden" id="questionId" value="">
                        
                        <label for="questionContent">题目内容:</label>
                        <textarea id="questionContent" style="height: 80px;" placeholder="请输入题目内容"></textarea>
                        
                        <label for="optionA">选项A:</label>
                        <input type="text" id="optionA" placeholder="选项A内容">
                        
                        <label for="optionB">选项B:</label>
                        <input type="text" id="optionB" placeholder="选项B内容">
                        
                        <label for="optionC">选项C:</label>
                        <input type="text" id="optionC" placeholder="选项C内容">
                        
                        <label for="optionD">选项D:</label>
                        <input type="text" id="optionD" placeholder="选项D内容">
                        
                        <label for="answer">正确答案:</label>
                        <select id="answer">
                            <option value="A">A</option>
                            <option value="B">B</option>
                            <option value="C">C</option>
                            <option value="D">D</option>
                        </select>
                        
                        <label for="knowledgePoint">知识点:</label>
                        <textarea id="knowledgePoint" style="height: 60px;" placeholder="请输入相关知识点"></textarea>
                        
                        <label for="questionBankSelect">所属题库:</label>
                        <select id="questionBankSelect">
                            <option value="">请选择题库（可选）</option>
                        </select>
                        
                        <div style="margin-top: 15px;">
                            <button type="submit" style="width: auto; margin-right: 10px;">保存题目</button>
                            <button type="button" onclick="hideQuestionForm()" style="width: auto; background-color: #6c757d;">取消</button>
                        </div>
                    </form>
                </div>
                
                <!-- 题目列表 -->
                <div id="questionsList"></div>
                <div id="questionsManageMessage"></div>
            </div>
            
            <div class="section">
                <h2>📊 班级管理与成绩查看</h2>
                
                <!-- 当前激活班级设置 -->
                <div style="background-color: #e7f3ff; padding: 15px; border-radius: 5px; margin-bottom: 20px; border-left: 4px solid #007bff;">
                    <h3 style="margin-top: 0; color: #0056b3;">🎯 当前激活班级设置</h3>
                    <p style="margin-bottom: 10px; color: #666;">选择的班级将成为当前激活班级，新的学生提交将自动归属于该班级。</p>
                    <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
                        <label for="activeClassSelect" style="margin: 0; font-weight: bold;">激活班级:</label>
                        <select id="activeClassSelect" style="width: auto; min-width: 120px;">
                            <option value="1">1班</option>
                            <option value="2">2班</option>
                            <option value="3">3班</option>
                            <option value="4">4班</option>
                            <option value="5">5班</option>
                            <option value="6">6班</option>
                            <option value="7">7班</option>
                            <option value="8">8班</option>
                            <option value="9">9班</option>
                            <option value="10">10班</option>
                            <option value="11">11班</option>
                            <option value="12">12班</option>
                            <option value="13">13班</option>
                            <option value="14">14班</option>
                            <option value="15">15班</option>
                            <option value="16">16班</option>
                            <option value="17">17班</option>
                        </select>
                        <button onclick="setActiveClass()" style="width: auto; background-color: #28a745; padding: 8px 16px;">设为激活班级</button>
                        <span id="currentActiveClass" style="color: #28a745; font-weight: bold;"></span>
                    </div>
                    <div id="activeClassMessage" style="margin-top: 10px;"></div>
                </div>
                
                <!-- 成绩查看 -->
                <div style="margin-bottom: 20px;">
                    <h3>📋 成绩查看</h3>
                    <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin-bottom: 15px;">
                        <label for="classSelect" style="margin: 0; font-weight: bold;">查看班级:</label>
                        <select id="classSelect" style="width: auto; min-width: 120px;">
                            <option value="1">1班</option>
                            <option value="2">2班</option>
                            <option value="3">3班</option>
                            <option value="4">4班</option>
                            <option value="5">5班</option>
                            <option value="6">6班</option>
                            <option value="7">7班</option>
                            <option value="8">8班</option>
                            <option value="9">9班</option>
                            <option value="10">10班</option>
                            <option value="11">11班</option>
                            <option value="12">12班</option>
                            <option value="13">13班</option>
                            <option value="14">14班</option>
                            <option value="15">15班</option>
                            <option value="16">16班</option>
                            <option value="17">17班</option>
                        </select>
                        <button onclick="loadScores()" style="width: auto; padding: 8px 16px;">查看成绩</button>
                    </div>
                </div>
                
                <!-- 危险操作区域 -->
                <div style="background-color: #fff3cd; padding: 15px; border-radius: 5px; margin-bottom: 20px; border-left: 4px solid #ffc107;">
                    <h3 style="margin-top: 0; color: #856404;">⚠️ 危险操作区域</h3>
                    <p style="margin-bottom: 15px; color: #856404;">以下操作不可恢复，请谨慎使用！</p>
                    <div style="display: flex; gap: 10px; flex-wrap: wrap;">
                        <button onclick="deleteClassSubmissions()" style="width: auto; background-color: #dc3545; padding: 8px 16px;">🗑️ 删除指定班级所有记录</button>
                        <button onclick="clearAllQuestions()" style="width: auto; background-color: #fd7e14; padding: 8px 16px;">🧹 清空所有题目</button>
                    </div>
                    <div id="dangerOperationMessage" style="margin-top: 10px;"></div>
                </div>
                
                <div id="scoresContainer"></div>
            </div>
            
            <div class="section">
                <h2>👥 学生做题记录查看</h2>

                <!-- 学生记录操作消息显示 -->
                <div id="studentRecordsMessage"></div>

                <!-- 搜索筛选条件 -->
                <div style="background-color: #f8f9fa; padding: 15px; border-radius: 5px; margin-bottom: 20px;">
                    <h3 style="margin-top: 0;">🔍 搜索筛选</h3>
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-bottom: 15px;">
                        <div>
                            <label for="studentNameFilter" style="margin-bottom: 5px;">学生姓名:</label>
                            <input type="text" id="studentNameFilter" placeholder="输入学生姓名" style="width: 100%; padding: 8px;">
                        </div>
                        <div>
                            <label for="classIdFilter" style="margin-bottom: 5px;">班级:</label>
                            <select id="classIdFilter" style="width: 100%; padding: 8px;">
                                <option value="">全部班级</option>
                                <option value="1">1班</option>
                                <option value="2">2班</option>
                                <option value="3">3班</option>
                                <option value="4">4班</option>
                                <option value="5">5班</option>
                                <option value="6">6班</option>
                                <option value="7">7班</option>
                                <option value="8">8班</option>
                                <option value="9">9班</option>
                                <option value="10">10班</option>
                                <option value="11">11班</option>
                                <option value="12">12班</option>
                                <option value="13">13班</option>
                                <option value="14">14班</option>
                                <option value="15">15班</option>
                                <option value="16">16班</option>
                                <option value="17">17班</option>
                            </select>
                        </div>
                        <div>
                            <label for="startDateFilter" style="margin-bottom: 5px;">开始日期:</label>
                            <input type="date" id="startDateFilter" style="width: 100%; padding: 8px;">
                        </div>
                        <div>
                            <label for="endDateFilter" style="margin-bottom: 5px;">结束日期:</label>
                            <input type="date" id="endDateFilter" style="width: 100%; padding: 8px;">
                        </div>
                    </div>
                    <div style="display: flex; gap: 10px; flex-wrap: wrap;">
                        <button onclick="searchStudentRecords()" style="width: auto; background-color: #007bff; padding: 8px 16px;">🔍 搜索记录</button>
                        <button onclick="clearFilters()" style="width: auto; background-color: #6c757d; padding: 8px 16px;">🧹 清空筛选</button>
                        <button onclick="exportStudentRecords()" style="width: auto; background-color: #28a745; padding: 8px 16px;">📊 导出数据</button>
                    </div>
                </div>
                
                <!-- 学生统计信息 -->
                <div id="studentStatsContainer" style="display: none; background-color: #e9ecef; padding: 15px; border-radius: 5px; margin-bottom: 20px;">
                    <h3 style="margin-top: 0;">📈 学生统计信息</h3>
                    <div id="studentStatsContent"></div>
                    <button onclick="hideStudentStats()" style="width: auto; background-color: #6c757d; padding: 8px 16px; margin-top: 10px;">关闭统计</button>
                </div>
                
                <!-- 记录列表 -->
                <div id="studentRecordsContainer">
                    <p style="text-align: center; color: #666; padding: 20px;">请使用上方搜索功能查看学生做题记录</p>
                </div>
                
                <div id="studentRecordsMessage"></div>
            </div>
            
            <!-- 学生做题详情模态框 -->
            <div id="submissionDetailModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); z-index: 1000;">
                <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 30px; border-radius: 10px; max-width: 90%; max-height: 90%; overflow-y: auto; width: 800px;">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; border-bottom: 2px solid #eee; padding-bottom: 15px;">
                        <h2 style="margin: 0; color: #333;">📝 学生做题详情</h2>
                        <button onclick="closeSubmissionDetail()" style="background: #dc3545; color: white; border: none; padding: 8px 12px; border-radius: 4px; cursor: pointer;">✕ 关闭</button>
                    </div>
                    <div id="submissionDetailContent"></div>
                </div>
            </div>
        </div>
        
        <script>
            // 通用日期格式化函数
            function formatDate(dateString, defaultValue = '1900-01-01 00:00:00') {
                try {
                    if (!dateString) {
                        return '未知时间';
                    }
                    const date = new Date(dateString);
                    if (isNaN(date.getTime())) {
                        return defaultValue;
                    }
                    return date.toLocaleString('zh-CN');
                } catch (e) {
                    console.warn('日期解析失败:', dateString, e);
                    return defaultValue;
                }
            }

            // 更新题目
            document.getElementById('questionsForm').addEventListener('submit', async function(e) {
                e.preventDefault();
                const questionsData = document.getElementById('questionsData').value;
                const messageDiv = document.getElementById('questionsMessage');
                
                if (!questionsData.trim()) {
                    messageDiv.innerHTML = '<div class="message error">请输入题目数据或描述</div>';
                    return;
                }
                
                // 显示加载状态
                const submitBtn = e.target.querySelector('button[type="submit"]');
                const originalText = submitBtn.textContent;
                submitBtn.textContent = '处理中...';
                submitBtn.disabled = true;
                
                try {
                    // 直接发送原始数据，让后端判断格式
                    const response = await fetch('/admin/questions', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'text/plain',
                        },
                        body: questionsData
                    });
                    
                    if (response.ok) {
                        const data = await response.json();
                        let message = data.message;
                        if (data.generated_count) {
                            message += `<br><br>生成了 ${data.generated_count} 道题目`;
                            if (data.generated_questions) {
                                // 显示生成的题目预览
                                const preview = data.generated_questions.slice(0, 2).map(q => 
                                    `${q.question_content} (答案: ${q.answer})`
                                ).join('<br>');
                                if (data.generated_questions.length > 2) {
                                    message += `<br><br>题目预览:<br>${preview}<br>... 还有 ${data.generated_questions.length - 2} 道题目`;
                                } else {
                                    message += `<br><br>生成的题目:<br>${preview}`;
                                }
                            }
                        }
                        messageDiv.innerHTML = `<div class="message success">${message}</div>`;
                        document.getElementById('questionsData').value = '';
                        loadQuestions(); // 刷新题目列表
                    } else {
                        const error = await response.text();
                        messageDiv.innerHTML = `<div class="message error">更新失败: ${error}</div>`;
                    }
                } catch (error) {
                    messageDiv.innerHTML = `<div class="message error">处理失败: ${error.message}</div>`;
                } finally {
                    // 恢复按钮状态
                    submitBtn.textContent = originalText;
                    submitBtn.disabled = false;
                }
            });
            
            // 加载成绩
            async function loadScores() {
                const classId = document.getElementById('classSelect').value;
                const container = document.getElementById('scoresContainer');
                
                try {
                    const response = await fetch(`/api/scores/${classId}`);
                    const scores = await response.json();
                    
                    if (scores.length === 0) {
                        container.innerHTML = '<p>今天该班级暂无提交记录。</p>';
                        return;
                    }
                    
                    let tableHTML = `
                        <table class="scores-table">
                            <thead>
                                <tr>
                                    <th>学生姓名</th>
                                    <th>得分</th>
                                    <th>提交时间</th>
                                    <th>客户端IP</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                    `;
                    
                    scores.forEach(score => {
                        tableHTML += `
                            <tr>
                                <td>${score.student_name}</td>
                                <td>${score.score}</td>
                                <td>${score.submission_time}</td>
                                <td>${score.client_ip || '未知'}</td>
                                <td>
                                    <button onclick="deleteSubmission(${score.submission_id})" 
                                            style="width: auto; padding: 5px 10px; font-size: 12px; background-color: #dc3545; color: white; border: none; border-radius: 3px; cursor: pointer;"
                                            onmouseover="this.style.backgroundColor='#c82333'" 
                                            onmouseout="this.style.backgroundColor='#dc3545'">删除</button>
                                </td>
                            </tr>
                        `;
                    });
                    
                    tableHTML += '</tbody></table>';
                    container.innerHTML = tableHTML;
                    
                } catch (error) {
                    container.innerHTML = `<div class="message error">加载成绩失败: ${error.message}</div>`;
                }
            }
            
            // 题库管理相关函数
            let currentQuestionBanks = [];
            
            // 加载题库列表
            async function loadQuestionBanks() {
                try {
                    const response = await fetch('/admin/question-banks');
                    const questionBanks = await response.json();
                    currentQuestionBanks = questionBanks;
                    displayQuestionBanks(questionBanks);
                    updateQuestionBankSelect(questionBanks);
                    updateFilterQuestionBankSelect(); // 更新筛选选择框
                    updateTargetQuestionBankSelect(); // 更新批量移动的目标题库选择框
                } catch (error) {
                    document.getElementById('questionBanksMessage').innerHTML = 
                        `<div class="message error">加载题库失败: ${error.message}</div>`;
                }
            }
            
            // 显示题库列表
            function displayQuestionBanks(questionBanks) {
                const container = document.getElementById('questionBanksList');
                
                if (questionBanks.length === 0) {
                    container.innerHTML = '<p>暂无题库数据。</p>';
                    return;
                }
                
                let html = `
                    <table class="scores-table">
                        <thead>
                            <tr>
                                <th style="width: 60px;">ID</th>
                                <th>题库名称</th>
                                <th>描述</th>
                                <th style="width: 80px;">题目数量</th>
                                <th style="width: 80px;">激活状态</th>
                                <th style="width: 120px;">创建时间</th>
                                <th style="width: 250px;">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                `;
                
                questionBanks.forEach(bank => {
                    const createdAt = formatDate(bank.created_time);

                    const statusText = bank.is_active ? '<span style="color: green; font-weight: bold;">已激活</span>' : '<span style="color: gray;">未激活</span>';
                    html += `
                        <tr>
                            <td>${bank.id}</td>
                            <td>${bank.name}</td>
                            <td>${bank.description || '无描述'}</td>
                            <td>${bank.question_count || 0}</td>
                            <td>${statusText}</td>
                            <td>${createdAt}</td>
                            <td>
                                <button onclick="viewQuestionBankDetail(${bank.id})" style="width: auto; margin-right: 5px; padding: 5px 10px; font-size: 12px; background-color: #17a2b8;">查看</button>
                                <button onclick="editQuestionBank(${bank.id})" style="width: auto; margin-right: 5px; padding: 5px 10px; font-size: 12px;">编辑</button>
                                ${!bank.is_active ? `<button onclick="activateQuestionBank(${bank.id})" style="width: auto; margin-right: 5px; padding: 5px 10px; font-size: 12px; background-color: #28a745;">激活</button>` : ''}
                                <button onclick="deleteQuestionBank(${bank.id})" style="width: auto; padding: 5px 10px; font-size: 12px; background-color: #dc3545;">删除</button>
                            </td>
                        </tr>
                    `;
                });
                
                html += '</tbody></table>';
                container.innerHTML = html;
            }
            
            // 更新题目表单中的题库选择下拉框
            function updateQuestionBankSelect(questionBanks) {
                const select = document.getElementById('questionBankSelect');
                select.innerHTML = '<option value="">请选择题库（可选）</option>';
                
                questionBanks.forEach(bank => {
                    const option = document.createElement('option');
                    option.value = bank.id;
                    option.textContent = bank.name;
                    select.appendChild(option);
                });
            }
            
            // 显示题库表单
            function showQuestionBankForm() {
                document.getElementById('bankFormTitle').textContent = '创建新题库';
                document.getElementById('questionBankId').value = '';
                document.getElementById('editQuestionBankForm').reset();
                document.getElementById('questionBankForm').style.display = 'block';
            }
            
            // 编辑题库
            function editQuestionBank(bankId) {
                const bank = currentQuestionBanks.find(b => b.id === bankId);
                if (!bank) return;
                
                document.getElementById('bankFormTitle').textContent = '编辑题库';
                document.getElementById('questionBankId').value = bank.id;
                document.getElementById('bankName').value = bank.name;
                document.getElementById('bankDescription').value = bank.description || '';
                document.getElementById('questionBankForm').style.display = 'block';
            }
            
            // 隐藏题库表单
            function hideQuestionBankForm() {
                document.getElementById('questionBankForm').style.display = 'none';
            }
            
            // 查看题库详情
            async function viewQuestionBankDetail(bankId) {
                try {
                    const response = await fetch(`/admin/question-banks/${bankId}`);
                    const bankDetail = await response.json();
                    
                    let detailHtml = `
                        <div style="background-color: #f8f9fa; padding: 20px; border-radius: 5px; margin: 20px 0;">
                            <h3>题库详情: ${bankDetail.name}</h3>
                            <p><strong>描述:</strong> ${bankDetail.description || '无描述'}</p>
                            <p><strong>题目数量:</strong> ${bankDetail.question_count}</p>
                            <p><strong>创建时间:</strong> ${formatDate(bankDetail.created_time)}</p>
                    `;
                    
                    if (bankDetail.questions && bankDetail.questions.length > 0) {
                        detailHtml += `
                            <h4>包含的题目 (共 ${bankDetail.questions.length} 道):</h4>
                            <div style="margin-top: 15px;">
                        `;

                        bankDetail.questions.forEach((question, index) => {
                            detailHtml += `
                                <div style="background-color: #ffffff; border: 1px solid #dee2e6; border-radius: 8px; padding: 20px; margin-bottom: 15px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                                        <h5 style="margin: 0; color: #495057;">📝 第 ${index + 1} 题 (ID: ${question.id})</h5>
                                        <div>
                                            <button onclick="editQuestionFromBank(${question.id})" style="width: auto; padding: 6px 12px; font-size: 12px; background-color: #007bff; margin-right: 8px; border-radius: 4px;">✏️ 编辑</button>
                                            <button onclick="moveQuestionFromBank(${question.id}, ${bankId})" style="width: auto; padding: 6px 12px; font-size: 12px; background-color: #ffc107; border-radius: 4px;">📤 移出</button>
                                        </div>
                                    </div>

                                    <div style="margin-bottom: 15px;">
                                        <strong style="color: #343a40;">题目内容:</strong>
                                        <div style="background-color: #f8f9fa; padding: 12px; border-radius: 4px; margin-top: 8px; border-left: 4px solid #007bff;">
                                            ${question.question_content}
                                        </div>
                                    </div>

                                    <div style="margin-bottom: 15px;">
                                        <strong style="color: #343a40;">选项:</strong>
                                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 8px;">
                                            <div style="background-color: #f8f9fa; padding: 10px; border-radius: 4px; border-left: 3px solid #28a745;">
                                                <strong>A.</strong> ${question.option_a}
                                            </div>
                                            <div style="background-color: #f8f9fa; padding: 10px; border-radius: 4px; border-left: 3px solid #ffc107;">
                                                <strong>B.</strong> ${question.option_b}
                                            </div>
                                            <div style="background-color: #f8f9fa; padding: 10px; border-radius: 4px; border-left: 3px solid #fd7e14;">
                                                <strong>C.</strong> ${question.option_c}
                                            </div>
                                            <div style="background-color: #f8f9fa; padding: 10px; border-radius: 4px; border-left: 3px solid #dc3545;">
                                                <strong>D.</strong> ${question.option_d}
                                            </div>
                                        </div>
                                    </div>

                                    <div style="display: flex; gap: 20px; margin-bottom: 10px;">
                                        <div style="background-color: #d4edda; padding: 8px 12px; border-radius: 4px; border: 1px solid #c3e6cb;">
                                            <strong style="color: #155724;">✅ 正确答案:</strong>
                                            <span style="color: #155724; font-weight: bold; font-size: 16px;">${question.answer}</span>
                                        </div>
                                        ${question.knowledge_point ? `
                                            <div style="background-color: #e2e3e5; padding: 8px 12px; border-radius: 4px; border: 1px solid #d6d8db;">
                                                <strong style="color: #383d41;">📚 知识点:</strong>
                                                <span style="color: #383d41;">${question.knowledge_point}</span>
                                            </div>
                                        ` : ''}
                                    </div>

                                    ${question.explanation ? `
                                        <div style="margin-top: 10px;">
                                            <strong style="color: #343a40;">💡 解析:</strong>
                                            <div style="background-color: #fff3cd; padding: 10px; border-radius: 4px; margin-top: 5px; border-left: 4px solid #ffc107;">
                                                ${question.explanation}
                                            </div>
                                        </div>
                                    ` : ''}
                                </div>
                            `;
                        });

                        detailHtml += '</div>';
                    } else {
                        detailHtml += '<p>该题库暂无题目。</p>';
                    }
                    
                    detailHtml += `
                            <div style="margin-top: 15px;">
                                <button onclick="this.parentElement.parentElement.remove()" style="width: auto; background-color: #6c757d;">关闭</button>
                            </div>
                        </div>
                    `;
                    
                    // 在题库列表后插入详情
                    const container = document.getElementById('questionBanksList');
                    container.insertAdjacentHTML('afterend', detailHtml);
                    
                } catch (error) {
                    document.getElementById('questionBanksMessage').innerHTML = 
                        `<div class="message error">加载题库详情失败: ${error.message}</div>`;
                }
            }
            
            // 删除题库
            async function deleteQuestionBank(bankId) {
                if (!confirm('确定要删除这个题库吗？题库中的题目将被移到默认题库。')) return;
                
                try {
                    const response = await fetch(`/admin/question-banks/${bankId}`, {
                        method: 'DELETE'
                    });
                    
                    if (response.ok) {
                        document.getElementById('questionBanksMessage').innerHTML = 
                            '<div class="message success">题库删除成功！</div>';
                        loadQuestionBanks();
                    } else {
                        const error = await response.text();
                        document.getElementById('questionBanksMessage').innerHTML = 
                            `<div class="message error">删除失败: ${error}</div>`;
                    }
                } catch (error) {
                    document.getElementById('questionBanksMessage').innerHTML = 
                        `<div class="message error">删除失败: ${error.message}</div>`;
                }
            }
            
            // 激活题库
            async function activateQuestionBank(bankId) {
                try {
                    const response = await fetch(`/admin/question-banks/${bankId}/activate`, {
                        method: 'POST'
                    });
                    
                    if (response.ok) {
                        const result = await response.json();
                        document.getElementById('questionBanksMessage').innerHTML = 
                            `<div class="message success">${result.message}</div>`;
                        loadQuestionBanks(); // 重新加载题库列表以更新激活状态
                        loadActiveQuestionBank(); // 重新加载当前激活题库显示
                    } else {
                        const error = await response.text();
                        document.getElementById('questionBanksMessage').innerHTML = 
                            `<div class="message error">激活失败: ${error}</div>`;
                    }
                } catch (error) {
                    document.getElementById('questionBanksMessage').innerHTML = 
                        `<div class="message error">激活失败: ${error.message}</div>`;
                }
            }
            
            // 加载当前激活的题库
            async function loadActiveQuestionBank() {
                try {
                    const response = await fetch('/admin/question-banks/active');
                    
                    if (response.ok) {
                        const result = await response.json();
                        if (result.bank) {
                            document.getElementById('currentActiveBank').innerHTML = 
                                `当前激活: <span style="color: #007bff;">${result.bank.name}</span> (ID: ${result.bank.id}, 题目数: ${result.bank.question_count || 0})`;
                        } else {
                            document.getElementById('currentActiveBank').innerHTML = 
                                '<span style="color: #dc3545;">当前没有激活的题库</span>';
                        }
                    } else {
                        document.getElementById('currentActiveBank').innerHTML = 
                            '<span style="color: #dc3545;">加载失败</span>';
                    }
                } catch (error) {
                    document.getElementById('currentActiveBank').innerHTML = 
                        '<span style="color: #dc3545;">加载失败</span>';
                    console.error('加载激活题库失败:', error);
                }
            }
            
            // 从题库中编辑题目
            async function editQuestionFromBank(questionId) {
                try {
                    const response = await fetch(`/admin/questions/${questionId}`);
                    const question = await response.json();
                    
                    // 填充题目编辑表单
                    document.getElementById('formTitle').textContent = '编辑题目';
                    document.getElementById('questionId').value = question.id;
                    document.getElementById('questionContent').value = question.question_content;
                    document.getElementById('optionA').value = question.option_a;
                    document.getElementById('optionB').value = question.option_b;
                    document.getElementById('optionC').value = question.option_c;
                    document.getElementById('optionD').value = question.option_d;
                    document.getElementById('answer').value = question.answer;
                    document.getElementById('knowledgePoint').value = question.knowledge_point;
                    document.getElementById('questionBankSelect').value = question.question_bank_id || '';
                    
                    // 显示题目编辑表单
                    document.getElementById('questionForm').style.display = 'block';
                    
                    // 滚动到表单位置
                    document.getElementById('questionForm').scrollIntoView({ behavior: 'smooth' });
                } catch (error) {
                    document.getElementById('questionBanksMessage').innerHTML = 
                        `<div class="message error">加载题目失败: ${error.message}</div>`;
                }
            }
            
            // 显示批量移动表单
            function showBatchMoveForm() {
                updateTargetQuestionBankSelect();
                updateSourceQuestionBankSelect();
                document.getElementById('batchMoveForm').style.display = 'block';
                document.getElementById('questionSelectionArea').style.display = 'none';
            }

            // 隐藏批量移动表单
            function hideBatchMoveForm() {
                document.getElementById('batchMoveForm').style.display = 'none';
                document.getElementById('targetQuestionBank').value = '';
                document.getElementById('sourceQuestionBank').value = '';
                document.getElementById('questionSelectionArea').style.display = 'none';
                document.getElementById('questionsList').innerHTML = '<div style="text-align: center; color: #666; padding: 20px;">请先选择源题库</div>';
                updateSelectionStats();
            }

            // 显示批量复制表单
            function showBatchCopyForm() {
                updateCopyTargetQuestionBankSelect();
                updateCopySourceQuestionBankSelect();
                document.getElementById('batchCopyForm').style.display = 'block';
                document.getElementById('copyQuestionSelectionArea').style.display = 'none';
            }

            // 隐藏批量复制表单
            function hideBatchCopyForm() {
                document.getElementById('batchCopyForm').style.display = 'none';
                document.getElementById('copyTargetQuestionBank').value = '';
                document.getElementById('copySourceQuestionBank').value = '';
                document.getElementById('copyQuestionSelectionArea').style.display = 'none';
                document.getElementById('copyQuestionsList').innerHTML = '<div style="text-align: center; color: #666; padding: 20px;">请先选择源题库</div>';
                updateCopySelectionStats();
            }
            
            // 更新目标题库选择下拉框
            function updateTargetQuestionBankSelect() {
                const select = document.getElementById('targetQuestionBank');
                select.innerHTML = '<option value="">请选择目标题库</option>';
                
                currentQuestionBanks.forEach(bank => {
                    const option = document.createElement('option');
                    option.value = bank.id;
                    option.textContent = bank.name;
                    select.appendChild(option);
                });
                
                // 添加"移出所有题库"选项
                const noneOption = document.createElement('option');
                noneOption.value = 'null';
                noneOption.textContent = '移出所有题库（设为无题库）';
                select.appendChild(noneOption);
            }

            // 更新源题库选择下拉框
            function updateSourceQuestionBankSelect() {
                const select = document.getElementById('sourceQuestionBank');
                select.innerHTML = '<option value="">请选择源题库</option>';

                if (currentQuestionBanks) {
                    currentQuestionBanks.forEach(bank => {
                        if (bank.question_count > 0) { // 只显示有题目的题库
                            const option = document.createElement('option');
                            option.value = bank.id;
                            option.textContent = `${bank.name} (${bank.question_count}题)`;
                            select.appendChild(option);
                        }
                    });
                }
            }

            // 加载源题库中的题目
            async function loadSourceQuestions() {
                const sourceBankId = document.getElementById('sourceQuestionBank').value;
                const questionsList = document.getElementById('questionsList');
                const selectionArea = document.getElementById('questionSelectionArea');

                if (!sourceBankId) {
                    selectionArea.style.display = 'none';
                    return;
                }

                try {
                    questionsList.innerHTML = '<div style="text-align: center; padding: 20px;"><i>正在加载题目...</i></div>';
                    selectionArea.style.display = 'block';

                    const response = await fetch(`/admin/question-banks/${sourceBankId}/questions`);
                    if (!response.ok) {
                        throw new Error('加载题目失败');
                    }

                    const questions = await response.json();

                    if (questions.length === 0) {
                        questionsList.innerHTML = '<div style="text-align: center; color: #666; padding: 20px;">该题库中没有题目</div>';
                        return;
                    }

                    // 生成题目列表HTML
                    let html = '';
                    questions.forEach((question, index) => {
                        const shortContent = question.question_content.length > 100
                            ? question.question_content.substring(0, 100) + '...'
                            : question.question_content;

                        html += `
                            <div style="border-bottom: 1px solid #eee; padding: 10px; margin-bottom: 5px;">
                                <label style="display: flex; align-items: flex-start; cursor: pointer;">
                                    <input type="checkbox" class="question-checkbox" value="${question.id}"
                                           onchange="updateSelectionStats()"
                                           style="margin-right: 10px; margin-top: 3px;">
                                    <div style="flex: 1;">
                                        <div style="font-weight: bold; margin-bottom: 5px;">题目 #${question.id}</div>
                                        <div style="color: #333; margin-bottom: 5px;">${shortContent}</div>
                                        <div style="font-size: 12px; color: #666;">
                                            <span style="margin-right: 15px;">📚 知识点: ${question.knowledge_point}</span>
                                            <span>✅ 答案: ${question.answer}</span>
                                        </div>
                                    </div>
                                </label>
                            </div>
                        `;
                    });

                    questionsList.innerHTML = html;
                    updateSelectionStats();

                } catch (error) {
                    questionsList.innerHTML = `<div style="text-align: center; color: #dc3545; padding: 20px;">加载失败: ${error.message}</div>`;
                }
            }

            // 全选题目
            function selectAllQuestions() {
                const checkboxes = document.querySelectorAll('.question-checkbox');
                checkboxes.forEach(checkbox => {
                    checkbox.checked = true;
                });
                updateSelectionStats();
            }

            // 取消全选
            function unselectAllQuestions() {
                const checkboxes = document.querySelectorAll('.question-checkbox');
                checkboxes.forEach(checkbox => {
                    checkbox.checked = false;
                });
                updateSelectionStats();
            }

            // 更新选择统计
            function updateSelectionStats() {
                const checkboxes = document.querySelectorAll('.question-checkbox');
                const selectedCheckboxes = document.querySelectorAll('.question-checkbox:checked');
                const selectedCount = selectedCheckboxes.length;
                const totalCount = checkboxes.length;

                const statsElement = document.getElementById('selectedCount');
                if (statsElement) {
                    statsElement.textContent = `已选择: ${selectedCount}`;
                }
            }

            // 复制功能相关函数

            // 更新复制目标题库选择下拉框
            function updateCopyTargetQuestionBankSelect() {
                const select = document.getElementById('copyTargetQuestionBank');
                select.innerHTML = '<option value="">请选择目标题库</option>';

                if (currentQuestionBanks) {
                    currentQuestionBanks.forEach(bank => {
                        const option = document.createElement('option');
                        option.value = bank.id;
                        option.textContent = `${bank.name} (${bank.question_count}题)`;
                        select.appendChild(option);
                    });
                }
            }

            // 更新复制源题库选择下拉框
            function updateCopySourceQuestionBankSelect() {
                const select = document.getElementById('copySourceQuestionBank');
                select.innerHTML = '<option value="">请选择源题库</option>';

                if (currentQuestionBanks) {
                    currentQuestionBanks.forEach(bank => {
                        if (bank.question_count > 0) { // 只显示有题目的题库
                            const option = document.createElement('option');
                            option.value = bank.id;
                            option.textContent = `${bank.name} (${bank.question_count}题)`;
                            select.appendChild(option);
                        }
                    });
                }
            }

            // 加载复制源题库中的题目
            async function loadCopySourceQuestions() {
                const sourceBankId = document.getElementById('copySourceQuestionBank').value;
                const questionsList = document.getElementById('copyQuestionsList');
                const selectionArea = document.getElementById('copyQuestionSelectionArea');

                if (!sourceBankId) {
                    selectionArea.style.display = 'none';
                    return;
                }

                try {
                    questionsList.innerHTML = '<div style="text-align: center; padding: 20px;"><i>正在加载题目...</i></div>';
                    selectionArea.style.display = 'block';

                    const response = await fetch(`/admin/question-banks/${sourceBankId}/questions`);
                    if (!response.ok) {
                        throw new Error('加载题目失败');
                    }

                    const questions = await response.json();

                    if (questions.length === 0) {
                        questionsList.innerHTML = '<div style="text-align: center; color: #666; padding: 20px;">该题库中没有题目</div>';
                        return;
                    }

                    // 生成题目列表HTML
                    let html = '';
                    questions.forEach((question, index) => {
                        const shortContent = question.question_content.length > 100
                            ? question.question_content.substring(0, 100) + '...'
                            : question.question_content;

                        html += `
                            <div style="border-bottom: 1px solid #eee; padding: 10px; margin-bottom: 5px;">
                                <label style="display: flex; align-items: flex-start; cursor: pointer;">
                                    <input type="checkbox" class="copy-question-checkbox" value="${question.id}"
                                           onchange="updateCopySelectionStats()"
                                           style="margin-right: 10px; margin-top: 3px;">
                                    <div style="flex: 1;">
                                        <div style="font-weight: bold; margin-bottom: 5px;">题目 #${question.id}</div>
                                        <div style="color: #333; margin-bottom: 5px;">${shortContent}</div>
                                        <div style="font-size: 12px; color: #666;">
                                            <span style="margin-right: 15px;">📚 知识点: ${question.knowledge_point}</span>
                                            <span>✅ 答案: ${question.answer}</span>
                                        </div>
                                    </div>
                                </label>
                            </div>
                        `;
                    });

                    questionsList.innerHTML = html;
                    updateCopySelectionStats();

                } catch (error) {
                    questionsList.innerHTML = `<div style="text-align: center; color: #dc3545; padding: 20px;">加载失败: ${error.message}</div>`;
                }
            }

            // 全选复制题目
            function selectAllCopyQuestions() {
                const checkboxes = document.querySelectorAll('.copy-question-checkbox');
                checkboxes.forEach(checkbox => {
                    checkbox.checked = true;
                });
                updateCopySelectionStats();
            }

            // 取消全选复制题目
            function unselectAllCopyQuestions() {
                const checkboxes = document.querySelectorAll('.copy-question-checkbox');
                checkboxes.forEach(checkbox => {
                    checkbox.checked = false;
                });
                updateCopySelectionStats();
            }

            // 更新复制选择统计
            function updateCopySelectionStats() {
                const checkboxes = document.querySelectorAll('.copy-question-checkbox');
                const selectedCheckboxes = document.querySelectorAll('.copy-question-checkbox:checked');
                const selectedCount = selectedCheckboxes.length;
                const totalCount = checkboxes.length;

                const statsElement = document.getElementById('copySelectedCount');
                if (statsElement) {
                    statsElement.textContent = `已选择: ${selectedCount}`;
                }
            }
            
            // 批量移动题目
            async function batchMoveQuestions() {
                const targetBankId = document.getElementById('targetQuestionBank').value;
                const selectedCheckboxes = document.querySelectorAll('.question-checkbox:checked');

                if (!targetBankId) {
                    showMessage('questionBankMessage', '❌ 请选择目标题库', 'error');
                    return;
                }

                if (selectedCheckboxes.length === 0) {
                    showMessage('questionBankMessage', '❌ 请至少选择一道题目', 'error');
                    return;
                }

                // 获取选中的题目ID
                const questionIds = Array.from(selectedCheckboxes).map(checkbox => parseInt(checkbox.value));

                // 确认操作
                const targetBankName = document.getElementById('targetQuestionBank').selectedOptions[0].textContent;
                if (!confirm(`确定要将 ${questionIds.length} 道题目移动到「${targetBankName}」吗？`)) {
                    return;
                }

                // 显示加载状态
                showMessage('questionBankMessage', '⏳ 正在批量移动题目，请稍候...', 'info', 0);

                try {
                    let successCount = 0;
                    let failCount = 0;

                    for (const questionId of questionIds) {
                        try {
                            const response = await fetch(`/admin/questions/${questionId}/move`, {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json',
                                },
                                body: JSON.stringify({
                                    question_bank_id: targetBankId === 'null' ? null : parseInt(targetBankId)
                                })
                            });

                            if (response.ok) {
                                successCount++;
                            } else {
                                failCount++;
                            }
                        } catch (error) {
                            failCount++;
                        }
                    }

                    if (failCount === 0) {
                        showMessage('questionBankMessage', `✅ 批量移动完成！成功移动 ${successCount} 道题目`, 'success');
                    } else {
                        showMessage('questionBankMessage', `⚠️ 批量移动完成！成功: ${successCount}，失败: ${failCount}`, 'warning');
                    }

                    hideBatchMoveForm();
                    loadQuestionBanks();
                    loadQuestions();
                } catch (error) {
                    showMessage('questionBankMessage', `❌ 批量移动失败: ${error.message}`, 'error');
                }
            }

            // 批量复制题目
            async function batchCopyQuestions() {
                const targetBankId = document.getElementById('copyTargetQuestionBank').value;
                const selectedCheckboxes = document.querySelectorAll('.copy-question-checkbox:checked');

                if (!targetBankId) {
                    showMessage('questionBankMessage', '❌ 请选择目标题库', 'error');
                    return;
                }

                if (selectedCheckboxes.length === 0) {
                    showMessage('questionBankMessage', '❌ 请至少选择一道题目', 'error');
                    return;
                }

                // 获取选中的题目ID
                const questionIds = Array.from(selectedCheckboxes).map(checkbox => parseInt(checkbox.value));

                // 确认操作
                const targetBankName = document.getElementById('copyTargetQuestionBank').selectedOptions[0].textContent;
                if (!confirm(`确定要将 ${questionIds.length} 道题目复制到「${targetBankName}」吗？\n\n注意：复制后原题库中的题目仍然保留。`)) {
                    return;
                }

                // 显示加载状态
                showMessage('questionBankMessage', '⏳ 正在批量复制题目，请稍候...', 'info', 0);

                try {
                    let successCount = 0;
                    let failCount = 0;

                    for (const questionId of questionIds) {
                        try {
                            const response = await fetch(`/admin/questions/${questionId}/copy`, {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json',
                                },
                                body: JSON.stringify({
                                    question_bank_id: parseInt(targetBankId)
                                })
                            });

                            if (response.ok) {
                                successCount++;
                            } else {
                                failCount++;
                            }
                        } catch (error) {
                            failCount++;
                        }
                    }

                    if (failCount === 0) {
                        showMessage('questionBankMessage', `✅ 批量复制完成！成功复制 ${successCount} 道题目`, 'success');
                    } else {
                        showMessage('questionBankMessage', `⚠️ 批量复制完成！成功: ${successCount}，失败: ${failCount}`, 'warning');
                    }

                    hideBatchCopyForm();
                    loadQuestionBanks();
                    loadQuestions();
                } catch (error) {
                    showMessage('questionBankMessage', `❌ 批量复制失败: ${error.message}`, 'error');
                }
            }
            
            // 从题库中移出题目
            async function moveQuestionFromBank(questionId, bankId) {
                if (!confirm('确定要将此题目移出当前题库吗？题目将被移到默认题库。')) return;
                
                try {
                    const response = await fetch(`/admin/questions/${questionId}/move`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({ question_bank_id: null })
                    });
                    
                    if (response.ok) {
                        document.getElementById('questionBanksMessage').innerHTML = 
                            '<div class="message success">题目移出成功！</div>';
                        // 重新加载题库详情
                        viewQuestionBankDetail(bankId);
                        loadQuestionBanks();
                    } else {
                        const error = await response.text();
                        document.getElementById('questionBanksMessage').innerHTML = 
                            `<div class="message error">移出失败: ${error}</div>`;
                    }
                } catch (error) {
                    document.getElementById('questionBanksMessage').innerHTML = 
                        `<div class="message error">移出失败: ${error.message}</div>`;
                }
            }
            
            // 题目管理相关变量和函数
            let currentQuestions = [];
            let filteredQuestions = [];
            
            // 更新筛选题库选择框
            function updateFilterQuestionBankSelect() {
                const select = document.getElementById('filterQuestionBank');
                if (!select) return;
                
                // 保存当前选中值
                const currentValue = select.value;
                
                // 清空选项
                select.innerHTML = '<option value="">全部题库</option>';
                
                // 添加题库选项
                currentQuestionBanks.forEach(bank => {
                    const option = document.createElement('option');
                    option.value = bank.id;
                    option.textContent = bank.name;
                    select.appendChild(option);
                });
                
                // 恢复选中值
                select.value = currentValue;
            }
            
            // 筛选题目
            function filterQuestions() {
                const searchTerm = document.getElementById('searchQuestion').value.toLowerCase();
                const selectedBankId = document.getElementById('filterQuestionBank').value;
                
                filteredQuestions = currentQuestions.filter(question => {
                    // 搜索关键词筛选
                    const matchesSearch = !searchTerm || 
                        question.question_content.toLowerCase().includes(searchTerm) ||
                        question.answer.toLowerCase().includes(searchTerm);
                    
                    // 题库筛选
                    const matchesBank = !selectedBankId || 
                        (question.question_bank_id && question.question_bank_id.toString() === selectedBankId);
                    
                    return matchesSearch && matchesBank;
                });
                
                displayQuestions(filteredQuestions);
                updateQuestionStats(); // 更新统计信息
            }
            
            // 清除筛选
            function clearFilters() {
                document.getElementById('searchQuestion').value = '';
                document.getElementById('filterQuestionBank').value = '';
                filteredQuestions = [...currentQuestions];
                displayQuestions(filteredQuestions);
                updateQuestionStats();
            }
            
            // 显示未分类题目
            function showUncategorizedQuestions() {
                document.getElementById('searchQuestion').value = '';
                document.getElementById('filterQuestionBank').value = '';
                filteredQuestions = currentQuestions.filter(question => !question.question_bank_id);
                displayQuestions(filteredQuestions);
                updateQuestionStats();
            }
            
            // 更新题目统计信息
            function updateQuestionStats() {
                const totalQuestions = currentQuestions.length;
                const filteredCount = filteredQuestions.length;
                const categorizedQuestions = currentQuestions.filter(q => q.question_bank_id).length;
                const uncategorizedQuestions = totalQuestions - categorizedQuestions;
                
                document.getElementById('totalQuestions').textContent = totalQuestions;
                document.getElementById('filteredQuestions').textContent = filteredCount;
                document.getElementById('categorizedQuestions').textContent = categorizedQuestions;
                document.getElementById('uncategorizedQuestions').textContent = uncategorizedQuestions;
            }
            
            // 加载题目列表
            async function loadQuestions() {
                try {
                    const response = await fetch('/admin/questions');
                    const questions = await response.json();
                    currentQuestions = questions;
                    filteredQuestions = [...questions];
                    
                    // 更新筛选选择框
                    updateFilterQuestionBankSelect();
                    
                    // 应用当前筛选条件
                    filterQuestions();
                    
                    // 更新统计信息
                    updateQuestionStats();
                } catch (error) {
                    showMessage('questionsManageMessage', `❌ 加载题目失败: ${error.message}`, 'error');
                }
            }
            
            // 显示题目列表
            function displayQuestions(questions) {
                const container = document.getElementById('questionsList');
                
                if (questions.length === 0) {
                    container.innerHTML = '<p>暂无题目数据。</p>';
                    return;
                }
                
                let html = `
                    <table class="scores-table">
                        <thead>
                            <tr>
                                <th style="width: 60px;">ID</th>
                                <th>题目内容</th>
                                <th style="width: 80px;">答案</th>
                                <th style="width: 120px;">所属题库</th>
                                <th style="width: 150px;">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                `;
                
                questions.forEach(question => {
                    // 查找题库名称
                    const questionBank = currentQuestionBanks.find(bank => bank.id === question.question_bank_id);
                    const bankName = questionBank ? questionBank.name : '无题库';
                    
                    html += `
                        <tr>
                            <td>${question.id}</td>
                            <td style="max-width: 300px; word-wrap: break-word;">${question.question_content}</td>
                            <td>${question.answer}</td>
                            <td style="color: ${questionBank ? '#007bff' : '#6c757d'};">${bankName}</td>
                            <td>
                                <button onclick="editQuestion(${question.id})" style="width: auto; margin-right: 5px; padding: 5px 10px; font-size: 12px;">编辑</button>
                                <button onclick="deleteQuestion(${question.id})" style="width: auto; padding: 5px 10px; font-size: 12px; background-color: #dc3545;">删除</button>
                            </td>
                        </tr>
                    `;
                });
                
                html += '</tbody></table>';
                container.innerHTML = html;
            }
            
            // 显示创建表单
            function showCreateForm() {
                document.getElementById('formTitle').textContent = '添加新题目';
                document.getElementById('questionId').value = '';
                document.getElementById('editQuestionForm').reset();
                document.getElementById('questionForm').style.display = 'block';
            }
            
            // 编辑题目
            function editQuestion(questionId) {
                const question = currentQuestions.find(q => q.id === questionId);
                if (!question) return;
                
                document.getElementById('formTitle').textContent = '编辑题目';
                document.getElementById('questionId').value = question.id;
                document.getElementById('questionContent').value = question.question_content;
                document.getElementById('optionA').value = question.option_a;
                document.getElementById('optionB').value = question.option_b;
                document.getElementById('optionC').value = question.option_c;
                document.getElementById('optionD').value = question.option_d;
                document.getElementById('answer').value = question.answer;
                document.getElementById('knowledgePoint').value = question.knowledge_point;
                document.getElementById('questionBankSelect').value = question.question_bank_id || '';
                document.getElementById('questionForm').style.display = 'block';
            }
            
            // 隐藏题目表单
            function hideQuestionForm() {
                document.getElementById('questionForm').style.display = 'none';
            }
            
            // 删除题目
            async function deleteQuestion(questionId) {
                if (!confirm('确定要删除这道题目吗？')) return;
                
                try {
                    const response = await fetch(`/admin/questions/${questionId}`, {
                        method: 'DELETE'
                    });
                    
                    if (response.ok) {
                        showMessage('questionsManageMessage', '✅ 题目删除成功！', 'success');
                        loadQuestions();
                    } else {
                        const error = await response.text();
                        showMessage('questionsManageMessage', `❌ 删除失败: ${error}`, 'error');
                    }
                } catch (error) {
                    showMessage('questionsManageMessage', `❌ 删除失败: ${error.message}`, 'error');
                }
            }
            
            // 删除提交记录
            async function deleteSubmission(submissionId) {
                if (!confirm('确定要删除这条提交记录吗？此操作不可撤销！')) return;
                
                try {
                    const response = await fetch(`/admin/submissions/${submissionId}`, {
                        method: 'DELETE'
                    });
                    
                    if (response.ok) {
                        // 重新加载当前班级的成绩
                        loadScores();
                    } else {
                        const error = await response.text();
                        alert(`删除失败: ${error}`);
                    }
                } catch (error) {
                    alert(`删除失败: ${error.message}`);
                }
            }
            
            // 保存题目表单
            document.getElementById('editQuestionForm').addEventListener('submit', async function(e) {
                e.preventDefault();
                
                const questionId = document.getElementById('questionId').value;
                const questionBankId = document.getElementById('questionBankSelect').value;
                const questionData = {
                    question_content: document.getElementById('questionContent').value,
                    option_a: document.getElementById('optionA').value,
                    option_b: document.getElementById('optionB').value,
                    option_c: document.getElementById('optionC').value,
                    option_d: document.getElementById('optionD').value,
                    answer: document.getElementById('answer').value,
                    knowledge_point: document.getElementById('knowledgePoint').value,
                    question_bank_id: questionBankId || null
                };
                
                try {
                    let response;
                    if (questionId) {
                        // 更新现有题目
                        response = await fetch(`/admin/questions/${questionId}`, {
                            method: 'PUT',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify(questionData)
                        });
                    } else {
                        // 创建新题目
                        response = await fetch('/admin/questions/create', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify(questionData)
                        });
                    }
                    
                    if (response.ok) {
                        showMessage('questionsManageMessage', '✅ 题目保存成功！', 'success');
                        hideQuestionForm();
                        loadQuestions();
                        loadQuestionBanks(); // 重新加载题库列表以更新题目数量
                    } else {
                        const error = await response.text();
                        showMessage('questionsManageMessage', `❌ 保存失败: ${error}`, 'error');
                    }
                } catch (error) {
                    showMessage('questionsManageMessage', `❌ 保存失败: ${error.message}`, 'error');
                }
            });
            
            // AI智能命题表单处理
            // 批量模式切换
            document.getElementById('batchMode').addEventListener('change', function() {
                const batchOptions = document.getElementById('batchModeOptions');
                const knowledgePointInput = document.getElementById('knowledgePointInput');
                
                if (this.checked) {
                    batchOptions.style.display = 'block';
                    knowledgePointInput.style.display = 'none';
                } else {
                    batchOptions.style.display = 'none';
                    knowledgePointInput.style.display = 'block';
                }
            });
            
            document.getElementById('aiGenerateForm').addEventListener('submit', async function(e) {
                e.preventDefault();
                
                const messageDiv = document.getElementById('aiGenerateMessage');
                const batchMode = document.getElementById('batchMode').checked;
                const questionCount = parseInt(document.getElementById('questionCount').value) || 5;
                const difficulty = document.getElementById('difficultyLevel').value || null;
                const topic = document.getElementById('topicCategory').value.trim() || null;
                
                let requestData = {
                    count: questionCount,
                    difficulty: difficulty,
                    topic: topic,
                    batch_mode: batchMode
                };
                
                if (batchMode) {
                    const batchPrompts = document.getElementById('batchPrompts').value.trim();
                    if (!batchPrompts) {
                        messageDiv.innerHTML = '<div class="message error">批量模式下请输入提示词列表！</div>';
                        return;
                    }
                    requestData.prompts = batchPrompts.split('\n').filter(p => p.trim()).map(p => p.trim());
                    requestData.knowledge_point = '批量生成';
                } else {
                    const knowledgePoint = document.getElementById('knowledgePointInput').value.trim();
                    if (!knowledgePoint) {
                        messageDiv.innerHTML = '<div class="message error">请输入知识点！</div>';
                        return;
                    }
                    requestData.knowledge_point = knowledgePoint;
                }
                
                // 显示加载状态
                const loadingText = batchMode ? 
                    `🤖 AI正在批量生成题目（${requestData.prompts ? requestData.prompts.length : 0}个知识点），请稍候...` :
                    '🤖 AI正在生成题目，请稍候...';
                messageDiv.innerHTML = `<div class="message">${loadingText}</div>`;
                
                try {
                    const response = await fetch('/admin/ai-generate', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(requestData)
                    });
                    
                    const result = await response.json();
                    
                    if (response.ok) {
                        let successMessage = `<div class="message success">${result.message}</div>`;
                        
                        // 显示生成信息
                        if (result.generation_info) {
                            const info = result.generation_info;
                            successMessage += `<div class="message info" style="margin-top: 10px;">` +
                                `📊 <strong>生成详情</strong><br>` +
                                `🔧 生成模式: ${info.mode === 'batch' ? '批量生成' : '单次生成'}<br>` +
                                `📝 题目数量: ${info.count} 道<br>` +
                                (info.difficulty ? `⭐ 难度等级: ${info.difficulty}<br>` : '') +
                                (info.topic ? `🏷️ 主题分类: ${info.topic}<br>` : '') +
                                (info.prompts_used > 1 ? `📚 处理知识点: ${info.prompts_used}个<br>` : '') +
                                `📁 新题库: ${info.new_bank.name}<br>` +
                                `📄 题库描述: ${info.new_bank.description}<br>` +
                                `✅ 题库状态: ${info.new_bank.is_active ? '已激活' : '未激活'}<br>` +
                                `</div>`;
                        }
                        
                        messageDiv.innerHTML = successMessage;
                        
                        // 清空输入框
                        if (batchMode) {
                            document.getElementById('batchPrompts').value = '';
                        } else {
                            document.getElementById('knowledgePointInput').value = '';
                        }
                        
                        // 刷新题目列表
                        loadQuestions();
                    } else {
                        messageDiv.innerHTML = `<div class="message error">生成失败: ${result.detail || result.message || '未知错误'}</div>`;
                    }
                } catch (error) {
                    messageDiv.innerHTML = `<div class="message error">生成失败: ${error.message}</div>`;
                }
            });
            
            // 大语言模型配置管理相关函数
            let currentLLMConfigs = [];
            
            // 加载配置列表
            async function loadLLMConfigs() {
                try {
                    console.log('Loading LLM configs...');
                    const response = await fetch('/admin/llm-configs');
                    const configs = await response.json();
                    console.log('Loaded configs:', configs);
                    currentLLMConfigs = configs;
                    displayLLMConfigs(configs);
                } catch (error) {
                    console.error('Error loading configs:', error);
                    document.getElementById('llmConfigMessage').innerHTML = 
                        `<div class="message error">加载配置失败: ${error.message}</div>`;
                }
            }
            
            // 显示配置列表
            function displayLLMConfigs(configs) {
                console.log('Displaying configs:', configs);
                const container = document.getElementById('llmConfigsList');
                
                if (configs.length === 0) {
                    container.innerHTML = '<p>暂无配置数据。</p>';
                    return;
                }
                
                let html = `
                    <table class="scores-table">
                        <thead>
                            <tr>
                                <th style="width: 60px;">ID</th>
                                <th>配置名称</th>
                                <th>Base URL</th>
                                <th>模型</th>
                                <th style="width: 80px;">状态</th>
                                <th style="width: 200px;">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                `;
                
                configs.forEach(config => {
                    const statusText = config.is_active ? '<span style="color: green;">激活</span>' : '<span style="color: gray;">未激活</span>';
                    html += `
                        <tr>
                            <td>${config.id}</td>
                            <td>${config.config_name}</td>
                            <td>${config.base_url}</td>
                            <td>${config.model_name}</td>
                            <td>${statusText}</td>
                            <td>
                                <button onclick="editLLMConfig(${config.id})" style="width: auto; margin-right: 5px; padding: 5px 10px; font-size: 12px;">编辑</button>
                                ${!config.is_active ? `<button onclick="activateLLMConfig(${config.id})" style="width: auto; margin-right: 5px; padding: 5px 10px; font-size: 12px; background-color: #28a745;">激活</button>` : ''}
                                <button onclick="deleteLLMConfig(${config.id})" style="width: auto; padding: 5px 10px; font-size: 12px; background-color: #dc3545;">删除</button>
                            </td>
                        </tr>
                    `;
                });
                
                html += '</tbody></table>';
                container.innerHTML = html;
            }
            
            // 显示配置表单
            function showLLMConfigForm() {
                document.getElementById('llmFormTitle').textContent = '添加新配置';
                document.getElementById('llmConfigId').value = '';
                document.getElementById('editLLMConfigForm').reset();
                // 移除默认值，让用户选择模板或手动填写
                document.getElementById('llmConfigForm').style.display = 'block';
            }
            
            // 模板填充函数
            function fillDeepSeekTemplate() {
                document.getElementById('configName').value = 'DeepSeek配置';
                document.getElementById('baseUrl').value = 'https://api.deepseek.com/v1';
                document.getElementById('modelName').value = 'deepseek-chat';
            }
            
            function fillGeminiTemplate() {
                document.getElementById('configName').value = 'Gemini配置';
                document.getElementById('baseUrl').value = 'https://generativelanguage.googleapis.com/v1beta/models';
                document.getElementById('modelName').value = 'gemini-2.0-flash';
            }
            
            function fillOpenAITemplate() {
                document.getElementById('configName').value = 'OpenAI配置';
                document.getElementById('baseUrl').value = 'https://api.openai.com/v1';
                document.getElementById('modelName').value = 'gpt-4';
            }
            
            function clearTemplate() {
                document.getElementById('configName').value = '';
                document.getElementById('baseUrl').value = '';
                document.getElementById('modelName').value = '';
                document.getElementById('apiKey').value = '';
                document.getElementById('isActive').checked = false;
            }
            
            // 编辑配置
            function editLLMConfig(configId) {
                console.log('editLLMConfig called with configId:', configId, 'type:', typeof configId);
                console.log('currentLLMConfigs:', currentLLMConfigs);
                
                // 确保ID类型匹配
                const config = currentLLMConfigs.find(c => c.id == configId);
                console.log('Found config:', config);
                
                if (!config) {
                    console.error('Config not found for id:', configId);
                    console.log('Available IDs:', currentLLMConfigs.map(c => ({id: c.id, type: typeof c.id})));
                    return;
                }
                
                document.getElementById('llmFormTitle').textContent = '编辑配置';
                document.getElementById('llmConfigId').value = config.id;
                document.getElementById('configName').value = config.config_name;
                document.getElementById('apiKey').value = config.api_key;
                document.getElementById('baseUrl').value = config.base_url;
                document.getElementById('modelName').value = config.model_name;
                document.getElementById('isActive').checked = config.is_active === 1;
                document.getElementById('llmConfigForm').style.display = 'block';
                
                console.log('Form should be visible now');
            }
            
            // 隐藏配置表单
            function hideLLMConfigForm() {
                document.getElementById('llmConfigForm').style.display = 'none';
            }
            
            // 激活配置
            async function activateLLMConfig(configId) {
                try {
                    const response = await fetch(`/admin/llm-configs/${configId}/activate`, {
                        method: 'POST'
                    });
                    
                    if (response.ok) {
                        document.getElementById('llmConfigMessage').innerHTML = 
                            '<div class="message success">配置激活成功！</div>';
                        loadLLMConfigs();
                    } else {
                        const error = await response.text();
                        document.getElementById('llmConfigMessage').innerHTML = 
                            `<div class="message error">激活失败: ${error}</div>`;
                    }
                } catch (error) {
                    document.getElementById('llmConfigMessage').innerHTML = 
                        `<div class="message error">激活失败: ${error.message}</div>`;
                }
            }
            
            // 删除配置
            async function deleteLLMConfig(configId) {
                if (!confirm('确定要删除这个配置吗？')) return;
                
                try {
                    const response = await fetch(`/admin/llm-configs/${configId}`, {
                        method: 'DELETE'
                    });
                    
                    if (response.ok) {
                        document.getElementById('llmConfigMessage').innerHTML = 
                            '<div class="message success">配置删除成功！</div>';
                        loadLLMConfigs();
                    } else {
                        const error = await response.text();
                        document.getElementById('llmConfigMessage').innerHTML = 
                            `<div class="message error">删除失败: ${error}</div>`;
                    }
                } catch (error) {
                    document.getElementById('llmConfigMessage').innerHTML = 
                        `<div class="message error">删除失败: ${error.message}</div>`;
                }
            }
            
            // 班级管理相关函数
            let currentActiveClass = 1; // 默认激活班级
            
            // 设置激活班级
            async function setActiveClass() {
                const classId = document.getElementById('activeClassSelect').value;
                if (!classId) {
                    document.getElementById('activeClassMessage').innerHTML = 
                        '<div class="message error">请选择班级！</div>';
                    return;
                }
                
                try {
                    const response = await fetch('/admin/class-config', {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body: `current_class_id=${classId}`
                    });
                    
                    if (response.ok) {
                        currentActiveClass = parseInt(classId);
                        const successMessage = `当前激活班级已设置为 ${classId} 班`;
                        document.getElementById('activeClassMessage').innerHTML = 
                            `<div class="message success">${successMessage}</div>`;
                        // 更新当前激活班级显示
                        document.getElementById('currentActiveClass').textContent = `当前激活: ${classId}班`;
                        // 弹窗提示成功
                        alert(`✅ ${successMessage}`);
                    } else {
                        const error = await response.text();
                        const errorMessage = `设置失败: ${error}`;
                        document.getElementById('activeClassMessage').innerHTML = 
                            `<div class="message error">${errorMessage}</div>`;
                        // 弹窗提示失败
                        alert(`❌ ${errorMessage}`);
                    }
                } catch (error) {
                    const errorMessage = `设置失败: ${error.message}`;
                    document.getElementById('activeClassMessage').innerHTML = 
                        `<div class="message error">${errorMessage}</div>`;
                    // 弹窗提示异常
                    alert(`❌ ${errorMessage}`);
                }
            }
            
            // 删除指定班级所有记录
            async function deleteClassSubmissions() {
                const classId = document.getElementById('classSelect').value;
                if (!classId) {
                    document.getElementById('dangerOperationMessage').innerHTML = 
                        '<div class="message error">请选择要删除的班级！</div>';
                    return;
                }
                
                if (!confirm(`确定要删除 ${classId} 班的所有学生记录吗？此操作不可恢复！`)) {
                    return;
                }
                
                try {
                    const response = await fetch(`/admin/class-submissions/${classId}`, {
                        method: 'DELETE'
                    });
                    
                    if (response.ok) {
                        document.getElementById('dangerOperationMessage').innerHTML = 
                            `<div class="message success">${classId} 班的所有学生记录已删除</div>`;
                        // 如果当前查看的是被删除的班级，刷新成绩列表
                        const currentViewClass = document.getElementById('classSelect').value;
                        if (currentViewClass == classId) {
                            loadScores();
                        }
                    } else {
                        const error = await response.text();
                        document.getElementById('dangerOperationMessage').innerHTML = 
                            `<div class="message error">删除失败: ${error}</div>`;
                    }
                } catch (error) {
                    document.getElementById('dangerOperationMessage').innerHTML = 
                        `<div class="message error">删除失败: ${error.message}</div>`;
                }
            }
            
            // 清空所有题目
            async function clearAllQuestions() {
                if (!confirm('确定要清空所有题目吗？此操作不可恢复！')) {
                    return;
                }
                
                try {
                    const response = await fetch('/admin/questions/clear-all', {
                        method: 'DELETE'
                    });
                    
                    if (response.ok) {
                        document.getElementById('dangerOperationMessage').innerHTML = 
                            '<div class="message success">所有题目已清空</div>';
                        // 刷新题目列表
                        loadQuestions();
                    } else {
                        const error = await response.text();
                        document.getElementById('dangerOperationMessage').innerHTML = 
                            `<div class="message error">清空失败: ${error}</div>`;
                    }
                } catch (error) {
                    document.getElementById('dangerOperationMessage').innerHTML = 
                        `<div class="message error">清空失败: ${error.message}</div>`;
                }
            }
            
            // 页面加载时获取当前激活班级
            async function loadActiveClass() {
                try {
                    const response = await fetch('/admin/class-config');
                    if (response.ok) {
                        const config = await response.json();
                        currentActiveClass = config.current_class_id;
                        document.getElementById('activeClassSelect').value = currentActiveClass;
                        // 更新当前激活班级显示
                        document.getElementById('currentActiveClass').textContent = `当前激活: ${currentActiveClass}班`;
                    }
                } catch (error) {
                    console.error('加载激活班级失败:', error);
                    document.getElementById('activeClassMessage').innerHTML = 
                        '<div class="message error">加载激活班级失败</div>';
                }
            }
            
            // 保存配置表单
            document.getElementById('editLLMConfigForm').addEventListener('submit', async function(e) {
                e.preventDefault();
                
                const configId = document.getElementById('llmConfigId').value;
                const configData = {
                    config_name: document.getElementById('configName').value,
                    api_key: document.getElementById('apiKey').value,
                    base_url: document.getElementById('baseUrl').value,
                    model_name: document.getElementById('modelName').value,
                    is_active: document.getElementById('isActive').checked ? 1 : 0
                };
                
                try {
                    let response;
                    if (configId) {
                        // 更新现有配置
                        response = await fetch(`/admin/llm-configs/${configId}`, {
                            method: 'PUT',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify(configData)
                        });
                    } else {
                        // 创建新配置
                        response = await fetch('/admin/llm-configs', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify(configData)
                        });
                    }
                    
                    if (response.ok) {
                        document.getElementById('llmConfigMessage').innerHTML = 
                            '<div class="message success">配置保存成功！</div>';
                        hideLLMConfigForm();
                        loadLLMConfigs();
                    } else {
                        const error = await response.text();
                        document.getElementById('llmConfigMessage').innerHTML = 
                            `<div class="message error">保存失败: ${error}</div>`;
                    }
                } catch (error) {
                    document.getElementById('llmConfigMessage').innerHTML = 
                        `<div class="message error">保存失败: ${error.message}</div>`;
                }
            });
            
            // 题库表单提交处理
            document.getElementById('questionBankForm').addEventListener('submit', async function(e) {
                e.preventDefault();
                
                const questionBankId = document.getElementById('questionBankId').value;
                const questionBankData = {
                    name: document.getElementById('bankName').value,
                    description: document.getElementById('bankDescription').value
                };
                
                try {
                    let response;
                    if (questionBankId) {
                        // 更新现有题库
                        response = await fetch(`/admin/question-banks/${questionBankId}`, {
                            method: 'PUT',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify(questionBankData)
                        });
                    } else {
                        // 创建新题库
                        response = await fetch('/admin/question-banks', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify(questionBankData)
                        });
                    }
                    
                    if (response.ok) {
                        showMessage('questionBankMessage', '✅ 题库保存成功！', 'success');
                        hideQuestionBankForm();
                        loadQuestionBanks();
                        updateQuestionBankSelect();
                    } else {
                        const error = await response.text();
                        showMessage('questionBankMessage', `❌ 保存失败: ${error}`, 'error');
                    }
                } catch (error) {
                    showMessage('questionBankMessage', `❌ 保存失败: ${error.message}`, 'error');
                }
            });
            
            // 学生做题记录查看功能
            async function searchStudentRecords() {
                const studentName = document.getElementById('studentNameFilter').value.trim();
                const classId = document.getElementById('classIdFilter').value;
                const startDate = document.getElementById('startDateFilter').value;
                const endDate = document.getElementById('endDateFilter').value;
                
                try {
                    const params = new URLSearchParams();
                    if (studentName) params.append('student_name', studentName);
                    if (classId) params.append('class_id', classId);
                    if (startDate) params.append('start_date', startDate);
                    if (endDate) params.append('end_date', endDate);
                    params.append('limit', '100');
                    
                    const response = await fetch(`/api/student-records?${params.toString()}`);
                    if (response.ok) {
                        const data = await response.json();
                        displayStudentRecords(data.records);
                        document.getElementById('studentRecordsMessage').innerHTML = 
                            `<div class="message info">找到 ${data.records.length} 条记录</div>`;
                    } else {
                        const error = await response.text();
                        document.getElementById('studentRecordsMessage').innerHTML = 
                            `<div class="message error">搜索失败: ${error}</div>`;
                    }
                } catch (error) {
                    document.getElementById('studentRecordsMessage').innerHTML = 
                        `<div class="message error">搜索失败: ${error.message}</div>`;
                }
            }
            
            function displayStudentRecords(records) {
                const container = document.getElementById('studentRecordsContainer');
                
                if (records.length === 0) {
                    container.innerHTML = '<p style="text-align: center; color: #666; padding: 20px;">未找到符合条件的记录</p>';
                    return;
                }
                
                let html = `
                    <table class="scores-table">
                        <thead>
                            <tr>
                                <th>学生姓名</th>
                                <th>班级</th>
                                <th>得分</th>
                                <th>正确率</th>
                                <th>题目数</th>
                                <th>提交日期</th>
                                <th>提交时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                `;
                
                records.forEach(record => {
                    html += `
                        <tr>
                            <td>${record.student_name}</td>
                            <td>${record.class_id}班</td>
                            <td style="font-weight: bold; color: ${record.score >= 80 ? '#28a745' : record.score >= 60 ? '#ffc107' : '#dc3545'};">${record.score}</td>
                            <td>${record.accuracy_rate}%</td>
                            <td>${record.correct_answers}/${record.total_questions}</td>
                            <td>${record.submission_date}</td>
                            <td>${formatDate(record.submission_time)}</td>
                            <td>
                                <button onclick="viewSubmissionDetail(${record.id})" style="width: auto; padding: 4px 8px; background-color: #007bff; margin-right: 5px;">查看详情</button>
                                <button onclick="showStudentStats('${record.student_name}', ${record.class_id})" style="width: auto; padding: 4px 8px; background-color: #17a2b8;">学生统计</button>
                            </td>
                        </tr>
                    `;
                });
                
                html += '</tbody></table>';
                container.innerHTML = html;
            }
            
            async function viewSubmissionDetail(submissionId) {
                try {
                    const response = await fetch(`/api/student-records/${submissionId}`);
                    if (response.ok) {
                        const data = await response.json();
                        displaySubmissionDetail(data);
                    } else {
                        const error = await response.text();
                        alert(`获取详情失败: ${error}`);
                    }
                } catch (error) {
                    alert(`获取详情失败: ${error.message}`);
                }
            }
            
            function displaySubmissionDetail(data) {
                const submission = data.submission;
                const questions = data.question_details;
                
                let html = `
                    <div style="background-color: #f8f9fa; padding: 15px; border-radius: 5px; margin-bottom: 20px;">
                        <h3 style="margin-top: 0;">📊 提交信息</h3>
                        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">
                            <div><strong>学生姓名:</strong> ${submission.student_name}</div>
                            <div><strong>班级:</strong> ${submission.class_id}班</div>
                            <div><strong>得分:</strong> <span style="color: ${submission.score >= 80 ? '#28a745' : submission.score >= 60 ? '#ffc107' : '#dc3545'}; font-weight: bold;">${submission.score}</span></div>
                            <div><strong>正确率:</strong> ${submission.accuracy_rate}%</div>
                            <div><strong>答对题数:</strong> ${submission.correct_answers}/${submission.total_questions}</div>
                            <div><strong>提交时间:</strong> ${formatDate(submission.submission_time)}</div>
                        </div>
                    </div>
                    
                    <h3>📝 答题详情</h3>
                    <div style="max-height: 400px; overflow-y: auto;">
                `;
                
                questions.forEach((q, index) => {
                    const isCorrect = q.is_correct;
                    const bgColor = isCorrect ? '#d4edda' : '#f8d7da';
                    const borderColor = isCorrect ? '#c3e6cb' : '#f5c6cb';
                    
                    html += `
                        <div style="background-color: ${bgColor}; border: 1px solid ${borderColor}; padding: 15px; margin-bottom: 15px; border-radius: 5px;">
                            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                                <h4 style="margin: 0;">第${index + 1}题 ${isCorrect ? '✅' : '❌'}</h4>
                                <span style="font-size: 12px; color: #666;">知识点: ${q.knowledge_point || '未分类'}</span>
                            </div>
                            <p style="margin-bottom: 10px;"><strong>题目:</strong> ${q.question_content}</p>
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 10px;">
                                <div>A. ${q.option_a}</div>
                                <div>B. ${q.option_b}</div>
                                <div>C. ${q.option_c}</div>
                                <div>D. ${q.option_d}</div>
                            </div>
                            <div style="display: flex; gap: 20px; margin-bottom: 10px;">
                                <div><strong>学生答案:</strong> <span style="color: ${isCorrect ? '#28a745' : '#dc3545'}; font-weight: bold;">${q.selected_answer}</span></div>
                                <div><strong>正确答案:</strong> <span style="color: #28a745; font-weight: bold;">${q.correct_answer}</span></div>
                            </div>
                            ${q.explanation ? `<div style="background-color: rgba(255,255,255,0.7); padding: 10px; border-radius: 3px;"><strong>解析:</strong> ${q.explanation}</div>` : ''}
                        </div>
                    `;
                });
                
                html += '</div>';
                
                document.getElementById('submissionDetailContent').innerHTML = html;
                document.getElementById('submissionDetailModal').style.display = 'block';
            }
            
            async function showStudentStats(studentName, classId) {
                try {
                    const response = await fetch(`/api/student-statistics/${encodeURIComponent(studentName)}?class_id=${classId}`);
                    if (response.ok) {
                        const stats = await response.json();
                        displayStudentStats(stats);
                    } else {
                        const error = await response.text();
                        alert(`获取统计失败: ${error}`);
                    }
                } catch (error) {
                    alert(`获取统计失败: ${error.message}`);
                }
            }
            
            function displayStudentStats(stats) {
                let html = `
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-bottom: 20px;">
                        <div style="text-align: center; background-color: white; padding: 15px; border-radius: 5px;">
                            <div style="font-size: 24px; font-weight: bold; color: #007bff;">${stats.total_submissions}</div>
                            <div>总提交次数</div>
                        </div>
                        <div style="text-align: center; background-color: white; padding: 15px; border-radius: 5px;">
                            <div style="font-size: 24px; font-weight: bold; color: #28a745;">${stats.average_score}</div>
                            <div>平均分</div>
                        </div>
                        <div style="text-align: center; background-color: white; padding: 15px; border-radius: 5px;">
                            <div style="font-size: 24px; font-weight: bold; color: #17a2b8;">${stats.overall_accuracy_rate}%</div>
                            <div>总体正确率</div>
                        </div>
                        <div style="text-align: center; background-color: white; padding: 15px; border-radius: 5px;">
                            <div style="font-size: 24px; font-weight: bold; color: #ffc107;">${stats.highest_score}</div>
                            <div>最高分</div>
                        </div>
                    </div>
                    
                    <h4>📈 最近5次提交记录</h4>
                    <table class="scores-table">
                        <thead>
                            <tr>
                                <th>提交时间</th>
                                <th>得分</th>
                                <th>正确率</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                `;
                
                stats.recent_submissions.forEach(sub => {
                    html += `
                        <tr>
                            <td>${formatDate(sub.submission_time)}</td>
                            <td style="font-weight: bold; color: ${sub.score >= 80 ? '#28a745' : sub.score >= 60 ? '#ffc107' : '#dc3545'};">${sub.score}</td>
                            <td>${sub.accuracy_rate}%</td>
                            <td><button onclick="viewSubmissionDetail(${sub.id})" style="width: auto; padding: 4px 8px; background-color: #007bff;">查看详情</button></td>
                        </tr>
                    `;
                });
                
                html += '</tbody></table>';
                
                document.getElementById('studentStatsContent').innerHTML = html;
                document.getElementById('studentStatsContainer').style.display = 'block';
            }
            
            function clearFilters() {
                document.getElementById('studentNameFilter').value = '';
                document.getElementById('classIdFilter').value = '';
                document.getElementById('startDateFilter').value = '';
                document.getElementById('endDateFilter').value = '';
                document.getElementById('studentRecordsContainer').innerHTML = '<p style="text-align: center; color: #666; padding: 20px;">请使用上方搜索功能查看学生做题记录</p>';
                document.getElementById('studentRecordsMessage').innerHTML = '';
            }
            
            function hideStudentStats() {
                document.getElementById('studentStatsContainer').style.display = 'none';
            }
            
            function closeSubmissionDetail() {
                document.getElementById('submissionDetailModal').style.display = 'none';
            }
            
            async function exportStudentRecords() {
                const studentName = document.getElementById('studentNameFilter').value.trim();
                const classId = document.getElementById('classIdFilter').value;
                const startDate = document.getElementById('startDateFilter').value;
                const endDate = document.getElementById('endDateFilter').value;

                // 显示导出格式选择对话框
                const format = prompt('请选择导出格式:\n1. excel (Excel文件)\n2. csv (CSV文件)\n3. pdf (PDF文件)\n\n请输入格式名称:', 'excel');

                if (!format || !['excel', 'csv', 'pdf'].includes(format.toLowerCase())) {
                    alert('❌ 请选择有效的导出格式 (excel/csv/pdf)');
                    return;
                }

                try {
                    showMessage('studentRecordsMessage', '📊 正在导出数据，请稍候...', 'info');

                    const params = new URLSearchParams();
                    if (studentName) params.append('student_name', studentName);
                    if (classId) params.append('class_id', classId);
                    if (startDate) params.append('start_date', startDate);
                    if (endDate) params.append('end_date', endDate);
                    params.append('format_type', format.toLowerCase());

                    const response = await fetch(`/admin/export/student-records?${params.toString()}`, {
                        method: 'GET',
                        headers: {
                            'Authorization': `Bearer ${localStorage.getItem('admin_token') || 'admin_secret_token_2024'}`
                        }
                    });

                    if (response.ok) {
                        // 获取文件名
                        const contentDisposition = response.headers.get('Content-Disposition');
                        let filename = `学生记录导出_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.${format}`;
                        if (contentDisposition) {
                            const filenameMatch = contentDisposition.match(/filename=(.+)/);
                            if (filenameMatch) {
                                filename = filenameMatch[1];
                            }
                        }

                        // 下载文件
                        const blob = await response.blob();
                        const url = window.URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = filename;
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                        window.URL.revokeObjectURL(url);

                        showMessage('studentRecordsMessage', '✅ 数据导出成功！', 'success');
                    } else {
                        const errorData = await response.json();
                        showMessage('studentRecordsMessage', `❌ 导出失败: ${errorData.detail || '未知错误'}`, 'error');
                    }
                } catch (error) {
                    console.error('导出失败:', error);
                    showMessage('studentRecordsMessage', '❌ 导出失败，请检查网络连接', 'error');
                }
            }

            // 通用消息显示函数
            function showMessage(elementId, message, type = 'info', duration = 5000) {
                const element = document.getElementById(elementId);
                if (!element) return;

                const messageClass = type === 'success' ? 'message success' :
                                   type === 'error' ? 'message error' :
                                   type === 'warning' ? 'message warning' : 'message info';

                // 清除之前的消息
                element.innerHTML = '';

                // 创建新消息元素
                const messageDiv = document.createElement('div');
                messageDiv.className = messageClass;
                messageDiv.style.animation = 'slideIn 0.3s ease-out';
                messageDiv.innerHTML = message;
                element.appendChild(messageDiv);

                // 自动清除消息
                if (duration > 0) {
                    setTimeout(() => {
                        if (element.contains(messageDiv)) {
                            messageDiv.classList.add('fade-out');
                            setTimeout(() => {
                                if (element.contains(messageDiv)) {
                                    element.removeChild(messageDiv);
                                }
                            }, 300); // 等待淡出动画完成
                        }
                    }, duration);
                }
            }

            // 页面加载时自动加载1班成绩、题目列表、配置列表、激活班级和题库列表
            window.addEventListener('load', function() {
                loadScores();
                loadQuestions();
                loadLLMConfigs();
                loadActiveClass();
                loadQuestionBanks();
                loadActiveQuestionBank();
            });
        </script>
    </body>
    </html>
    